package com.itxg.booksmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxg.booksmanage.entity.User;
import com.itxg.booksmanage.mapper.UserMapper;
import com.itxg.booksmanage.service.UserService;
import com.itxg.booksmanage.utils.RandomSalt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        String account = user.getAccount();
        String password = user.getPassword();
        if (StringUtils.hasText(account) && StringUtils.hasText(password)) {
            // 1. 查询数据库，获取用户盐值和密文
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("account", account);
            User queryUser = userMapper.selectOne(wrapper);
            if (!StringUtils.isEmpty(queryUser)) {
                // 2. 盐值（salt）和用户提供的密码（password），使用相同的哈希算法重新计算密码的哈希值
                String encryptPassword = RandomSalt.encryptPassword(password, queryUser.getSalt());
                if (queryUser.getPassword().equals(encryptPassword)) {
                    // 3. 如果密文和数据库的匹配成功，则登录成功
                    // 4. 移除敏感字段，返回前端
                    queryUser.setPassword("");
                    queryUser.setSalt("");
                    return queryUser;
                }
            }
        }
        return null;
    }

    @Override
    public int regist(User user) {
        String account = user.getAccount();
        String password = user.getPassword();
        // 1. 判断数据库中是否存在该用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account);
        User one = userMapper.selectOne(wrapper);
        if (one != null) {
            System.out.println("用户名已存在");
            return -2; // 用户已存在
        }
        if (StringUtils.hasText(account) && StringUtils.hasText(password)) {
            // 2. 生成盐值
            String salt = RandomSalt.generateSalt();
            // 3. 使用盐值对密码进行加密
            password = RandomSalt.encryptPassword(password, salt);
            user.setPassword(password);
            user.setSalt(salt);
            // 4. 将账号、密文密码，盐值一起写入数据库
            if (userMapper.insert(user) > 0) {
                System.out.println("注册成功");
                return 1;
            }
        }
        System.out.println("注册失败");
        return -1;
    }
}

